#ifdef _3DS
  #include <3ds.h>
#endif
#include <stdio.h>


#include "lprefix.h"
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

static int pmain(lua_State *L)
{
  int argc = (int)lua_tointeger(L, 1);
  char **argv = (char **)lua_touserdata(L, 2);

  luaL_openlibs(L);
  luaL_loadfile(L, "main.lua");
  lua_pcall(L, 0, 0, 0);
  lua_pushboolean(L, 1);

  return 1;
}

int initLua()
{
  int status, result;
  lua_State *L = luaL_newstate();

  if (L == NULL) {
    return -1;
  }

  lua_pushcfunction(L, &pmain);  /* to call 'pmain' in protected mode */
  lua_pushinteger(L, 0);  /* 1st argument */
  lua_pushlightuserdata(L, 0); /* 2nd argument */
  status = lua_pcall(L, 2, 1, 0);  /* do the call */
  result = lua_toboolean(L, -1);  /* get result */

  lua_close(L);

  return result;
}

int main(int argc, char **argv)
{
#ifdef _3DS
  gfxInitDefault();
  consoleInit(GFX_TOP, NULL);
#endif

printf("HELLO WORLD FROM C\n");

  initLua();

#ifdef _3DS
        // Main loop
        while (aptMainLoop())
        {
                //Scan all the inputs. This should be done once for each frame
                hidScanInput();
                
                //hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
                u32 kDown = hidKeysDown();
                
                if (kDown & KEY_START) break; // break in order to return to hbmenu
                
                // Flush and swap framebuffers
                gfxFlushBuffers();
                gfxSwapBuffers(); 
                
                //Wait for VBlank
                gspWaitForVBlank();
        }
         
        gfxExit();
#endif

        return 0; 
}
